package com.project.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.project.bean.UserBean;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.time.LocalDate;
import java.util.List;

@Controller
@RequestMapping("user")
public class UserController {

    @RequestMapping("leaf")
    public String  thymeleafPress(HttpServletRequest request){
        request.setAttribute("name","张三");
        request.setAttribute("grade",80);
        List<UserBean> list = List.of(
                new UserBean(1,"李同", LocalDate.parse("1998-03-04"),8000),
                new UserBean(2,"刘勇", LocalDate.parse("1995-08-30"),7000),
                new UserBean(3,"朱军", LocalDate.parse("1986-05-21"),9000)
                );
        request.setAttribute("list",list);

        return "/leaf.html";
    }
    @RequestMapping("add")
    @ResponseBody
    public String add(@Valid UserBean user, BindingResult result) throws Exception {
        if(result.hasErrors()){//判断是否有错误信息
            //得到所有错误信息
            List<FieldError> errorList = result.getFieldErrors();
            ObjectMapper om = new ObjectMapper();
            return om.writeValueAsString(errorList);
        }

        System.out.println("执行添加操作");
        return "ok";
    }
}
